package com.example.jf.jfapp;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.jf.jfapp.activity.base.BaseActivity;
import com.example.jf.jfapp.bean.ChooseImageBean;
import com.example.jf.jfapp.bean.request.SendBlogRequest;
import com.example.jf.jfapp.bean.response.PictureResponse;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.google.gson.Gson;

import org.apache.http.util.EncodingUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AnnounceBlogActivity extends BaseActivity {

    @BindView(R.id.announce_back)
    ImageView announceBack;
    @BindView(R.id.tv_sendblog)
    AppCompatTextView tvSendblog;
    @BindView(R.id.sendblog)
    AppCompatTextView sendblog;
    @BindView(R.id.et_send_content)
    AppCompatEditText etSendContent;
    @BindView(R.id.et_edit_content)
    AppCompatEditText etEditContent;
    @BindView(R.id.ablum)
    ImageView ablum;
    @BindView(R.id.camera)
    ImageView camera;
    @BindView(R.id.sendBlogplane)
    ImageView sendBlogplane;

    File outputImage;
    String filename = "imagepa";


    //返回数据的key
    public final static String STATU_SEND_RESULT_KEY = "STATU_SEND_RESULT_KEY";

    //启动相册请求码
    public static final int START_PICK_CODE = 0;


    public static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.et_edit_content2)
    AppCompatEditText etEditContent2;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.et_edit_content3)
    AppCompatEditText etEditContent3;
    @BindView(R.id.image3)
    ImageView image3;

    int size = 0;
    @BindView(R.id.cancel1)
    ImageView cancel1;
    @BindView(R.id.frame1)
    FrameLayout frame1;
    @BindView(R.id.cancel2)
    ImageView cancel2;
    @BindView(R.id.frame2)
    FrameLayout frame2;
    @BindView(R.id.cancel3)
    ImageView cancel3;
    @BindView(R.id.frame3)
    FrameLayout frame3;

    private Uri imageUri;
    int blogType = 1;

    ArrayList<ChooseImageBean> mChooseImageBeens = new ArrayList<>();
    ArrayList<Uri> mUris = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_announce_blog);
        ButterKnife.bind(this);
        blogType = getIntent().getIntExtra(STATU_SEND_RESULT_KEY, 0);

        if (blogType == 1) {
            tvSendblog.setText("杂谈");
        }
        if (blogType == 2) {
            tvSendblog.setText("提问");
        }
        if (blogType == 3) {
            tvSendblog.setText("分享");
        }

        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                String[] languages = getResources().getStringArray(R.array.languages);
                // String[] languages = getResources().getStringArray(R.color.accent);
//                Toast.makeText(this, , 2000).show();
                Toast.makeText(AnnounceBlogActivity.this, "你点击的是:" + languages[pos], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

    }

    @OnClick({R.id.announce_back, R.id.ablum, R.id.camera, R.id.sendBlogplane,R.id.sendblog})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.announce_back:
                finish();
                break;
            case R.id.ablum:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }

                break;
            case R.id.camera:
                // 创建File对象，用于存储拍照后的图片

                File outputImage = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
                try {
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT < 24) {
                    imageUri = Uri.fromFile(outputImage);
                } else {
                    imageUri = FileProvider.getUriForFile(this, "com.example.cameraalbumtest.fileprovider", outputImage);
                }
                mUris.add(imageUri);
                // 启动相机程序
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO);
                break;
            case R.id.sendBlogplane:

                if (mUris.size()==0 ) {
                    getDongtai();
                    return;
                }
                    getPicture();

                break;
            case R.id.sendblog:
                if (mUris.size()==0 ) {
                    getDongtai();
                    return;
                }
                getPicture();
                break;
        }
    }

    int mCurrnetIndex = 0;

    private void getPicture() {

//        for (int i = 0; i < mChooseImageBeens.size(); i++) {
//            if(mChooseImageBeens.get(i).getType() == TYPE_IMAGE) {
//                mUris.add(mChooseImageBeens.get(i).getUri());
//            }
//        }
        if (mUris != null && !mUris.isEmpty()) {
            uri = mUris.get(mCurrnetIndex);
        }
        mCurrnetIndex = mCurrnetIndex + 1;
        File imagePath2 = new File((getRealFilePath(AnnounceBlogActivity.this, uri)));

        OkHttpClient client = new OkHttpClient();
        //String imagepath=readFileData(filename);
        //outputImage = new File(imagepath);
        MediaType IMAGETYPE = MediaType.parse("image/jpg");
        RequestBody body = RequestBody.create(IMAGETYPE, imagePath2);
        Request request = new Request.Builder()
                .post(body)
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "image/jpg")
                .url("https://api.leancloud.cn/1.1/files/" + System.currentTimeMillis() + ".jpg")//后缀名需要自行判断修改，如图片格式有：jpg  jpeg png
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d(TAG, "打开图片失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "上传图片返回值" + result);

                Gson gson = new Gson();
                PictureResponse pictureResponse = gson.fromJson(result, PictureResponse.class);
                String image = pictureResponse.getUrl();

                picimages.add(image);

                if (mCurrnetIndex < mUris.size()) {

                    getPicture();

                }
                if (picimages.size() == mUris.size()) {
                    getDongtai(picimages);
                }

            }
        });
    }

    //图片的集合
    ArrayList<String> picimages = new ArrayList<>();

    //  int mCurrnetIndex = 0;
    Uri uri;

    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private void getDongtai(ArrayList<String> picimages) {

        OkHttpClient client = new OkHttpClient();
        MediaType JSONTYPE = MediaType.parse("application/json; charset=utf-8");
        String url = "https://leancloud.cn:443/1.1/functions/issueBlog";
        Gson gons = new Gson();
        String content1 = etEditContent.getText().toString();
        String content2 = etEditContent2.getText().toString();
        String content3 = etEditContent3.getText().toString();
        ArrayList<String> contentArr = new ArrayList<>();
        if (content1 != "") {
            contentArr.add(content1);
        }
        if (content2 != "") {
            contentArr.add(content2);
        }
        if (content3 != "") {
            contentArr.add(content3);
        }


        //if (picimages != null && !picimages.isEmpty()) {
            contentArr.addAll(picimages);
      //  }
//测试


        String userId = AppConfigUtils.getInstance().getLoginInfo(this).getObjectId();
        if (userId == "" || userId.isEmpty() || userId == null) {
            Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            return;
        }
//        Intent intent=getIntent();
//        String userId=intent.getStringExtra("userId");

        String title = etSendContent.getText().toString();
        SendBlogRequest Blogrequest = new SendBlogRequest();
        Blogrequest.setUserId(userId);
        Blogrequest.setTitle(title);
        Blogrequest.setContentArr(contentArr);
        Blogrequest.setBlogType(blogType);


        String jsonData = gons.toJson(Blogrequest);//将需要提交的数据转为Json格式
        RequestBody body = RequestBody.create(JSONTYPE, jsonData);
//        HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
//        builder.addQueryParameter("userId",userId)
//                .addQueryParameter("content",content)
//                .addQueryParameter("image",image);

        final Request request = new Request.Builder()
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "application/json")
                .url(url)//
                .post(body)//
                .build();//
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取动态数据shibai");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "获取动态数据 " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (response.code() == 200) {


                            Log.e(TAG, "onResponse: 上传第" + mCurrnetIndex + "图片成功了");
                            Toast.makeText(AnnounceBlogActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }
    private void getDongtai() {

        OkHttpClient client = new OkHttpClient();
        MediaType JSONTYPE = MediaType.parse("application/json; charset=utf-8");
        String url = "https://leancloud.cn:443/1.1/functions/issueBlog";
        Gson gons = new Gson();
        String content1 = etEditContent.getText().toString();
        String content2 = etEditContent2.getText().toString();
        String content3 = etEditContent3.getText().toString();
        ArrayList<String> contentArr = new ArrayList<>();
        if (content1 != "") {
            contentArr.add(content1);
        }
        if (content2 != "") {
            contentArr.add(content2);
        }
        if (content3 != "") {
            contentArr.add(content3);
        }


        String userId = AppConfigUtils.getInstance().getLoginInfo(this).getObjectId();
        if (userId == "" || userId.isEmpty() || userId == null) {
            Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            return;
        }
//        Intent intent=getIntent();
//        String userId=intent.getStringExtra("userId");

        String title = etSendContent.getText().toString();
        SendBlogRequest Blogrequest = new SendBlogRequest();
        Blogrequest.setUserId(userId);
        Blogrequest.setTitle(title);
        Blogrequest.setContentArr(contentArr);
        Blogrequest.setBlogType(blogType);


        String jsonData = gons.toJson(Blogrequest);//将需要提交的数据转为Json格式
        RequestBody body = RequestBody.create(JSONTYPE, jsonData);
//        HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
//        builder.addQueryParameter("userId",userId)
//                .addQueryParameter("content",content)
//                .addQueryParameter("image",image);

        final Request request = new Request.Builder()
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "application/json")
                .url(url)//
                .post(body)//
                .build();//
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取动态数据shibai");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "获取动态数据 " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (response.code() == 200) {
                            Toast.makeText(AnnounceBlogActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/jpg");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // case 111:
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        //picture.setImageBitmap(bitmap);
                        if (size == 0) {
                            frame1.setVisibility(View.VISIBLE);
                            image1.setImageBitmap(bitmap);
                            cancel1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mUris.remove(2);
                                    frame1.setVisibility(View.GONE);
                                }
                            });
                            size = size + 1;
                            return;
                        }
                        if (size == 1) {
                            frame2.setVisibility(View.VISIBLE);
                            image2.setImageBitmap(bitmap);
                            cancel2.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mUris.remove(2);
                                    frame2.setVisibility(View.GONE);
                                }
                            });
                            size = size + 1;
                            return;
                        }
                        if (size == 2) {
                            frame3.setVisibility(View.VISIBLE);
                            image3.setImageBitmap(bitmap);
                            cancel3.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mUris.remove(2);
                                    frame3.setVisibility(View.GONE);
                                }
                            });
                            return;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片

    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);


    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);


        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        mUris.add(uri);
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            //album.setVisibility(View.VISIBLE);
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            if (size == 0) {
                frame1.setVisibility(View.VISIBLE);
                image1.setImageBitmap(bitmap);
                cancel1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mUris.remove(0);
                        frame1.setVisibility(View.GONE);
                        //image1.notify();
                    }
                });
                size = size + 1;
                return;
            }
            if (size == 1) {
                frame2.setVisibility(View.VISIBLE);
                image2.setImageBitmap(bitmap);
                cancel2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mUris.remove(1);
                        frame2.setVisibility(View.GONE);
                    }
                });
                size = size + 1;
                return;
            }
            if (size == 2) {
                frame3.setVisibility(View.VISIBLE);
                image3.setImageBitmap(bitmap);
                cancel3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mUris.remove(2);
                        frame3.setVisibility(View.GONE);
                    }
                });
                return;
            }


//            else {
//                if(image2==null){
//                    image2.setImageBitmap(bitmap);
//                    return;
//                }else {
//                    image3.setImageBitmap(bitmap);
//                }
//            }

//            outputImage = new File(imagePath);
//
//            try {
//                if (outputImage.exists()) {
//                    outputImage.delete();
//                }
//                outputImage.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            writeFileData(filename, imagePath);

        }
    }

    //写文件
    public void writeFileData(String fileName, String message) {
        try {
            FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
            byte[] bytes = message.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读文件
    public String readFileData(String fileName) {
        String res = "";
        try {
            FileInputStream fin = openFileInput(fileName);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            res = EncodingUtils.getString(buffer, "UTF-8");
            fin.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

}
